/*
 * @Author: lll 1280388921@qq.com
 * @Date: 2025-05-29 21:31:42
 * @LastEditors: lll 1280388921@qq.com
 * @LastEditTime: 2025-06-13 23:57:06
 * @FilePath: /lesson41/udp/UdpClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <cstring>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h>
#include "log.hpp"
#include "Terminal.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "\n\rUsage: " << proc << " serverip serverport\n"
         << endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int socketfd;
    string ip;
};

void *recv_meg(void *args)
{
    OpenTerm();
    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[1024];
    while (1)
    {
        memset(buffer,0,sizeof(buffer));
        struct sockaddr_in tmp;
        socklen_t llen = sizeof(tmp);
        ssize_t s = recvfrom(td->socketfd, buffer, 1023, 0, (struct sockaddr *)&tmp, &llen);
        if (s > 0)
        {
            buffer[s] = 0;
            cerr << buffer << endl;
        }
    }
}

void *send_meg(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    string msg;
    socklen_t len = sizeof(td->server);
    string welcome = td->ip;
    welcome += " is coming...\n";
    sendto(td->socketfd, welcome.c_str(), welcome.size(), 0, (struct sockaddr *)&(td->server), len);

    while (1)
    {
        cout << "Please Enter: ";
        getline(cin, msg);
        sendto(td->socketfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}

// 多线程 一个输入，一个收消息（输出）

// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    ThreadData td;
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    td.ip = serverip;

    td.socketfd = socket(AF_INET, SOCK_DGRAM, 0); // PF_INET
    if (td.socketfd < 0)
    {
        cout << "client socket create error " << endl;
        exit(1);
    }

    // client 要bind吗   需要！
    // client 也要有自己的ip和port
    // 只不过不需要用户显示的绑定
    // 一般由OS自由随机选择port的绑定
    // 一个端口号只能被一个进程bind，对于server是如此，对于client也是如此
    // 如果允许客户端固定绑定端口号就可能会导致其他程序也绑定了同一个端口号，而导致其他程序运行不起来。
    // 其实client的port是多少并不重要，只要能保证主机上的唯一性就可以！
    // 系统什么时候bind呢 首次发送数据的时候！

    bzero(&td.server, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(serverport);
    td.server.sin_addr.s_addr = inet_addr(serverip.c_str());

    pthread_t csvr, sender;
    pthread_create(&csvr, nullptr, recv_meg, &td);
    pthread_create(&sender, nullptr, send_meg, &td);

    pthread_join(csvr, nullptr);
    pthread_join(sender, nullptr);

    close(td.socketfd);
    return 0;
}